import { FieldTimeOutlined } from '@ant-design/icons';
import { ProFormText } from '@ant-design/pro-components';
import { DatePicker } from 'antd';
import React, { useState } from 'react';
import styles from './index.less';
import { ToDatePickerType } from './typing';
const ToDatePicker: React.FC<ToDatePickerType> = (props) => {
  const { name, formRef, timePickerProps, timeChange, label, width } = props;
  const [datePickerOpen, setDatePickerOpen] = useState<boolean>(false);
  const commonFormChange = (e: any) => {
    e?.stopPropagation?.();
    setDatePickerOpen(false);
  };
  const assignForm = (value: string, e: any) => {
    formRef?.current?.setFieldValue([name], value);
    commonFormChange(e);
  };
  const addonAfter = (
    <div className={styles.addonAfter}>
      <div className={styles.tips} onClick={() => setDatePickerOpen(true)}>
        <span>日期选择</span> <FieldTimeOutlined style={{ fontSize: 15 }} />
      </div>
      <DatePicker
        picker="month"
        open={datePickerOpen}
        className={styles.datePicker}
        style={{ display: datePickerOpen ? 'block' : 'none' }}
        format="YYYY-MM"
        placeholder="请选择"
        onChange={(e: any, dateString: string) => {
          if (timeChange) {
            commonFormChange(e);
            timeChange(dateString);
            return;
          }
          assignForm(dateString, e);
        }}
        renderExtraFooter={() => (
          <div
            onClick={(e) => {
              if (timeChange) {
                commonFormChange(e);
                timeChange('至今');
                return;
              }
              assignForm('至今', e);
            }}
            className={styles.toDayText}
          >
            至今
          </div>
        )}
        {...timePickerProps}
      />
    </div>
  );
  return (
    <>
      <ProFormText
        className={styles.timePicker}
        width={width}
        label={label}
        {...props}
        fieldProps={{
          addonAfter,
          allowClear: false,
          onFocus: () => setDatePickerOpen(true),
        }}
      />
    </>
  );
};

export default ToDatePicker;
